package bh

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType

/**
 * Created by Lingbaeryi
 */

abstract class FR<T : ViewBinding> : Fragment(), View.OnClickListener {

    var mContext: Context? = null
    var viewBinding: T? = null
    private var isLoaded = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val type: ParameterizedType = javaClass.genericSuperclass as ParameterizedType
        val cls = type.actualTypeArguments[0] as Class<*>
        try {
            val inflate: Method = cls.getDeclaredMethod(
                "inflate",
                LayoutInflater::class.java,
                ViewGroup::class.java,
                Boolean::class.javaPrimitiveType
            )
            viewBinding = inflate.invoke(null, inflater, container, false) as T
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        }
        return viewBinding?.root
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.mContext = context
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewBinding.let {
            initView(viewBinding!!)
            initListener()
        }

    }

    override fun onResume() {
        super.onResume()
        if (!isLoaded) {
            isLoaded = true
            initData()
        }
    }


    /**
     * 控件初始化
     */
    open fun initView(view: T) {

    }

    /**
     * 加载数据方法 只会执行一次
     */
    open fun initData() {

    }

    /**
     * 点击事件监听
     */
    open fun initListener() {

    }

    /**
     * 点击事件
     */
    override fun onClick(v: View?) {

    }

    override fun onDestroy() {
        super.onDestroy()
        isLoaded = false
    }



}